package jsu.yym.tiktok.service;

import jsu.yym.tiktok.config.PasswordNotMatchedException;
import jsu.yym.tiktok.config.UserIsNullMatchedException;
import jsu.yym.tiktok.pojo.LoginUser;
import jsu.yym.tiktok.pojo.User;
import jsu.yym.tiktok.mapper.MenuMapper;
import jsu.yym.tiktok.mapper.UserMapper;
import jsu.yym.tiktok.server.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImp implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Resource
    private RedisCache redisCache;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
//        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(User::getUsername,username);
        System.out.println("username="+username);
        User user = userMapper.getUserByUserName(username);
        System.out.println(user+"user");
        if(Objects.isNull(user))
            throw new UserIsNullMatchedException("用户不存在");
        //从redis中获取密码
        String redisKey = "pwd:" + username;
        System.out.println(redisKey);
        String pwd = redisCache.getCacheObject(redisKey);


        System.out.println(pwd);
        System.out.println(user.getPassword());
        if (!pwd.equals(user.getPassword())) {
            // 密码不匹配时抛出自定义异常
            throw new PasswordNotMatchedException("密码错误");
        }
        //判断验证码是否相同
//        Set<String> permissions = menuMapper.selectPermsByUserId(username);
//        return new LoginUser(user,permissions);
        List<GrantedAuthority> auths= AuthorityUtils.commaSeparatedStringToAuthorityList(null);
        System.out.println(new BCryptPasswordEncoder().encode(user.getPassword()));
        return new LoginUser(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()),auths);

    }



}
